import PateoAuthButtons from '../../../components/common/PateoAuthButtons';
import PateoCropper from '../../../components/common/PateoCropper';
import PateoModalForm, { itemLayout } from '../../../components/common/PateoModalForm';
import PateoSearchForm from '../../../components/common/PateoSearchForm';
import PateoTable from '../../../components/common/PateoTable';
import styles from '../../../components/common/PateoTable/TableList.less';
import AddAdminModal from './addAdminModal';
import EditAdminModal from './editAdminModal';
import EditModal from './editModal';
import permissonStyle from './index.less';
import ResetPwdModal from './resetPwdModal';
import { comboHolder, comboSelectHolder, filterAuth } from '@/support/common';
import { ExclamationCircleFilled, PlusOutlined, QuestionCircleOutlined } from '@ant-design/icons';
import {
  Badge,
  Button,
  Card,
  Drawer,
  message,
  Space,
  Spin,
  Table,
  Tag,
  Radio,
  Checkbox,
  Tooltip,
  Tree,
  Form,
  Tabs,
} from 'antd';
import classnames from 'classnames';
import { connect } from 'dva';
import moment from 'moment';
import PropTypes from 'prop-types';
import React, { PureComponent } from 'react';

const { TreeNode } = Tree;
const CheckboxGroup = Checkbox.Group;
const { TabPane } = Tabs;
const itemTypes = {
  0: { value: '菜单', color: '#1890ff' },
  2: { value: '按钮', color: '#52c41a' },
  1: { value: '页面', color: '#f5222d' },
};
const mapStateToProps = (state: any) => ({
  tenant: state.tenant,
  loading: state.loading.effects['tenant/postFetchPage'],
  saveLoading: state.loading.effects['tenant/postObj'],
  detailLoading: state.loading.effects['tenant/getData'],
});
class Tenant extends PureComponent<any, any> {
  static contextTypes = {
    permissions: PropTypes.array,
  };

  constructor(props: any) {
    super(props);
    this.state = {
      formValues: {},
      rsVisible: false,
      rsAdminVisible: false,
      adminVisible: false,
      modalVisible: false,
      refreshLoading: false,
      rsList: [],
      rsAdminList: [],
      adminList: [],
      checkedKeys: {},
      adminCheckedKeys: {},
      expandedKeys: [],
      expandedAdminKeys: [],
      levelMap: null,
      tenantCode: null,
      tenantSid: null,
      tenantIsSelectAll: null,
      visible: false,
      postUrl: '',
      formData: {},
      cropper: {
        visible: false,
        src: '',
        key: '',
        logoUrl: '',
        thumbnailLogoUrl: '',
      },
      resetVisible: false,
      resetRecord: {},
      editAdminOpen: false,
      editAdminData: null,
      roleOption: [],
      orgOption: [],
      isSelectAll: 0,
      postSelectAll: 0,
      activeTabKey: 'brand',
      tabDisabled: false,
      brand: [],
      project: [],
      person: [],
      brandPermisionData: [],
      projectPermisionData: [],
      personPermisionData: [],
      brandCheckAll: false,
      projectCheckAll: false,
      personCheckAll: false,
    };
  }

  componentDidMount() {
    const { dispatch } = this.props;
    dispatch({
      type: 'tenant/postFetchPage',
      payload: { url: '/tenant/page' },
    });
    // this.getRoleOption();
    // this.getOrgOption();
  }

  //  获取租户数据权限数据
  getPermissionData = (type = 0, sid = '') => {
    //  type: 0 新增, 1 编辑; sid: 租户id
    const { dispatch } = this.props;
    let params: any = {
      operate: type,
    };
    if (type === 1) {
      params.sid = sid;
    }
    dispatch({
      type: 'tenant/getDataWithRes',
      payload: {
        url: '/tenant/getPermission',
        ...params,
      },
      callback: (res: any) => {
        if (res.statusCode === '0') {
          this.formatPermisionData(res.data, type);
        }
      },
    });
  };

  componentWillUnmount() {
    const { dispatch } = this.props;
    dispatch({
      type: 'tenant/initData',
    });
  }

  getRoleOption = () => {
    const { dispatch } = this.props;
    dispatch({
      type: 'http/getData',
      payload: {
        url: '/account/findrole',
      },
      callback: (response: any) => {
        // console.log('角色列表---', response)
        /* this.setState({
          roleData: response.data,
          roleOption: response.data ? transferOption(response.data, ['roleCode', 'roleName']) : [],
        }); */
      },
    });
  };

  getOrgOption = () => {
    const { dispatch } = this.props;
    dispatch({
      type: 'http/getData',
      payload: {
        url: '/account/findorgtree',
      },
      callback: (response: any) => {
        // console.log('组织树---', response)
        /* if (response.data) {
          this.setState({
            orgOption: this.fotmatOrgTree(response.data),
          });
        } */
      },
    });
  };

  fotmatOrgTree = data => {
    return data.map(d => {
      if (d.children) {
        this.fotmatOrgTree(d.children);
      }
      d.title = d.orgName;
      d.value = d.sid;
      return d;
    });
  };

  formatPermisionData = (data: any, type: any) => {
    if (!(data && data.length > 0)) return;
    let tempBrandPermisionData: Array<any> = [];
    let tempProjectPermisionData: Array<any> = [];
    let tempPersonPermisionData: Array<any> = [];
    let tempBrand: Array<any> = [];
    let tempProject: Array<any> = [];
    let tempPerson: Array<any> = [];
    data.forEach((item: any) => {
      const { sid, itemLevel, used } = item;
      const permisionItem = {
        value: sid,
        label: itemLevel,
      };
      if (item.itemType === 'BRAND') {
        tempBrandPermisionData.push(permisionItem);
        if (type === 1 && used === 1) {
          tempBrand.push(sid);
        }
        return;
      }
      if (item.itemType === 'PROJECT') {
        tempProjectPermisionData.push(permisionItem);
        if (type === 1 && used === 1) {
          tempProject.push(sid);
        }
        return;
      }
      if (item.itemType === 'PERSON') {
        tempPersonPermisionData.push(permisionItem);
        if (type === 1 && used === 1) {
          tempPerson.push(sid);
        }
        return;
      }
    });
    this.setState({
      brand: tempBrand,
      project: tempProject,
      person: tempPerson,
      brandPermisionData: tempBrandPermisionData,
      projectPermisionData: tempProjectPermisionData,
      personPermisionData: tempPersonPermisionData,
      brandCheckAll:
        tempBrandPermisionData.length > 0 && tempBrand.length === tempBrandPermisionData.length,
      projectCheckAll:
        tempProjectPermisionData.length > 0 &&
        tempProject.length === tempProjectPermisionData.length,
      personCheckAll:
        tempPersonPermisionData.length > 0 && tempPerson.length === tempPersonPermisionData.length,
    });
  };

  handleFlushPage = () => {
    const { dispatch } = this.props;
    const { formValues } = this.state;
    dispatch({
      type: 'tenant/postFetchPage',
      payload: { url: '/tenant/page', ...formValues },
    });
  };

  openResource = async (tenantCode: any) => {
    const { dispatch } = this.props;
    this.setState({ rsVisible: true });
    const response = await dispatch({
      type: 'tenant/getData',
      payload: {
        url: '/tenant/findtenantmgrpool',
        tenantCode: tenantCode,
      },
    });
    if (response.statusCode === '0') {
      let levelMap: any = new Map();
      let checked: any = [];
      let halfChecked: any = [];
      this.getCheckedKeys(response.data, checked, halfChecked);
      this.getLevelMap(response.data, levelMap);
      this.setState({
        rsList: response.data,
        checkedKeys: { checked: checked, halfChecked: halfChecked },
        levelMap: levelMap,
        tenantCode: tenantCode,
      });
    }
  };

  openAdminResource = async (tenantCode: any) => {
    const { dispatch } = this.props;
    const response = await dispatch({
      type: 'tenant/getData',
      payload: {
        url: '/tenant/findmgrresource',
        tenantCode: tenantCode,
      },
    });
    if (response.statusCode === '0') {
      if (!response.data || response.data.length == 0) {
        message.warning('请先设置租户菜单！');
        return;
      }
      let levelMap: any = new Map();
      let checked: any = [];
      let halfChecked: any = [];
      this.getCheckedKeys(response.data, checked, halfChecked);
      this.getLevelMap(response.data, levelMap);
      this.setState({
        rsAdminVisible: true,
        rsAdminList: response.data,
        adminCheckedKeys: { checked: checked, halfChecked: halfChecked },
        levelMap: levelMap,
        tenantCode: tenantCode,
      });
    }
  };

  openAdmin = async (tenantCode: any, sid: any, isSelectAll: any) => {
    const { dispatch } = this.props;
    const resp = await dispatch({
      type: 'tenant/getData',
      payload: {
        url: '/tenant/findmgrresource',
        tenantCode: tenantCode,
      },
    });
    if (resp.statusCode === '0') {
      if (!resp.data || resp.data.length == 0) {
        message.warning('请先设置租户菜单！');
        return;
      }
    } else {
      return;
    }
    this.setState({ adminVisible: true });
    const response = await dispatch({
      type: 'tenant/getData',
      payload: {
        url: '/tenant/findmgr',
        tenantCode: tenantCode,
      },
    });
    if (response.statusCode === '0') {
      this.setState({
        adminList: response.data,
        tenantCode: tenantCode,
        tenantSid: sid,
        tenantIsSelectAll: isSelectAll,
      });
    }
  };

  refresAdmin = () => {
    const { dispatch } = this.props;
    const { tenantCode } = this.state;
    this.setState({ refreshLoading: true });
    dispatch({
      type: 'tenant/getDataWithRes',
      payload: {
        url: '/tenant/findmgr',
        tenantCode: tenantCode,
      },
      callback: (res: any) => {
        this.setState({ refreshLoading: false });
        if (res.statusCode === '0') {
          this.setState({ adminList: res.data });
        } else {
          message.error(res.statusMessage);
        }
      },
    });
  };

  openModal = () => {
    this.setState({ modalVisible: true });
  };

  getCheckedKeys = (data: any, checked: any, halfChecked: any) => {
    data.map((item: any) => {
      if (item.checked == 1) {
        checked.push(item.resourceSid);
      }
      if (item.checked == 2) {
        halfChecked.push(item.resourceSid);
      }
      if (item.children && item.children.length > 0) {
        this.getCheckedKeys(item.children, checked, halfChecked);
      }
    });
  };

  getLevelMap = (data: any, map: any) => {
    data.map((item: any) => {
      map.set(item.resourceSid, item.resourceLevel);
      if (item.children && item.children.length > 0) {
        this.getLevelMap(item.children, map);
      }
    });
  };

  closeResource = () => {
    this.setState({
      rsVisible: false,
      rsList: [],
      expandedKeys: [],
      checkedKeys: {},
      levelMap: null,
      tenantCode: null,
    });
  };

  closeAdminResource = () => {
    this.setState({
      rsAdminVisible: false,
      rsAdminList: [],
      expandedAdminKeys: [],
      adminCheckedKeys: {},
      levelMap: null,
      tenantCode: null,
    });
  };

  closeAdmin = () => {
    this.setState({ adminVisible: false, adminList: [], refreshLoading: false, tenantCode: null });
  };

  closeModal = () => {
    this.setState({ modalVisible: false });
  };

  renderTreeNodes = (data: any) => {
    return (
      data &&
      data.map((item: any) => {
        if (item.children && item.children.length > 0) {
          return (
            <TreeNode
              title={
                <span>
                  <Tag
                    style={{ marginRight: 0 }}
                    color={
                      typeof item.resourceType === 'number' && itemTypes[item.resourceType].color
                    }
                  >
                    {item.resourceName}
                  </Tag>
                </span>
              }
              key={item.resourceSid}
            >
              {this.renderTreeNodes(item.children)}
            </TreeNode>
          );
        } else {
          delete item.children;
        }
        return (
          <TreeNode
            key={item.resourceSid}
            title={
              item.resourceType !== 0 ? (
                <Tag
                  style={{ marginRight: 0 }}
                  color={
                    typeof item.resourceType === 'number' && itemTypes[item.resourceType].color
                  }
                >
                  {item.resourceName}
                </Tag>
              ) : (
                <span>
                  <Tag
                    style={{ marginRight: 0 }}
                    color={
                      typeof item.resourceType == 'number' && itemTypes[item.resourceType].color
                    }
                  >
                    {item.resourceName}
                  </Tag>
                </span>
              )
            }
          />
        );
      })
    );
  };

  onCheck = (checkedKeys: any, e: any) => {
    const checkedObj = { checked: checkedKeys, halfChecked: e.halfCheckedKeys };
    this.setState({ checkedKeys: { ...checkedObj } });
  };

  onAdminCheck = (checkedKeys: any, e: any) => {
    const checkedObj = { checked: checkedKeys, halfChecked: e.halfCheckedKeys };
    this.setState({ adminCheckedKeys: { ...checkedObj } });
  };

  onResourceSubmit = () => {
    const { dispatch } = this.props;
    const { checkedKeys, tenantCode, levelMap } = this.state;
    let resourceList: any = [];
    checkedKeys.checked &&
      checkedKeys.checked.length > 0 &&
      checkedKeys.checked.map((item: any) => {
        resourceList.push({ resourceSid: item, resourceLevel: levelMap.get(item) });
      });
    checkedKeys.halfChecked &&
      checkedKeys.halfChecked.length > 0 &&
      checkedKeys.halfChecked.map((item: any) => {
        resourceList.push({ resourceSid: item, resourceLevel: levelMap.get(item) });
      });
    let params: any = { tenantCode: tenantCode, resourceList: resourceList };
    dispatch({
      type: 'tenant/postObj',
      payload: {
        url: '/tenant/resourceconfig',
        ...params,
      },
      callback: (res: any) => {
        message.success('保存成功');
        this.closeResource();
      },
    });
  };

  onAdminResourceSubmit = () => {
    const { dispatch } = this.props;
    const { adminCheckedKeys, tenantCode } = this.state;
    let resourceList: any = [];
    adminCheckedKeys.checked &&
      adminCheckedKeys.checked.length > 0 &&
      adminCheckedKeys.checked.map((item: any) => {
        resourceList.push(item);
      });
    adminCheckedKeys.halfChecked &&
      adminCheckedKeys.halfChecked.length > 0 &&
      adminCheckedKeys.halfChecked.map((item: any) => {
        resourceList.push(item);
      });
    let params: any = { tenantCode: tenantCode, resourceList: resourceList };
    dispatch({
      type: 'tenant/postObj',
      payload: {
        url: '/tenant/edittenantrole',
        ...params,
      },
      callback: (res: any) => {
        message.success('保存成功');
        this.closeAdminResource();
      },
    });
  };

  handleAdd = () => {
    this.getPermissionData(0);
    this.setState({
      visible: true,
      postUrl: '/tenant/add',
      cropper: {
        logoUrl: '',
        thumbnailLogoUrl: '',
      },
      formData: {
        isSelectAll: 0,
      },
    });
  };

  handleEdit = (record: any) => {
    let data = { ...record };
    // data.sid = data.tenantCode;
    data.loginMode = String(data.loginMode);
    data.mgrViewOtherAccount = String(data.mgrViewOtherAccount);
    data.mgrViewOtherRole = String(data.mgrViewOtherRole);
    this.getPermissionData(1, record.sid);
    // let tabDisabled = data.isSelectAll === 1 ? true : false
    this.setState({
      formData: data,
      visible: true,
      postUrl: '/tenant/edit',
      cropper: {
        logoUrl: data.logoUrl,
        thumbnailLogoUrl: data.thumbnailLogoUrl,
      },
      isSelectAll: data.isSelectAll,
      postSelectAll: data.isSelectAll,
      // tabDisabled
    });
  };

  permissionValidator = () => {
    const { brand, project, person } = this.state;
    const tempList = [...brand, ...project, ...person];
    return tempList.length > 0;
  };

  onSelectAllChange = (v: number) => {
    if (v === 1) {
      const { brandPermisionData, projectPermisionData, personPermisionData } = this.state;
      const tempBrand = brandPermisionData.map(function (item: any) {
        return item.value;
      });
      const tempProject = projectPermisionData.map(function (item: any) {
        return item.value;
      });
      const tempPerson = personPermisionData.map(function (item: any) {
        return item.value;
      });

      this.setState({
        activeTabKey: 'brand',
        // tabDisabled: true,
        brand: tempBrand,
        project: tempProject,
        person: tempPerson,
        brandCheckAll: true,
        projectCheckAll: true,
        personCheckAll: true,
        postSelectAll: 1,
      });
    } else {
      /* this.setState({
        tabDisabled: false
      }) */
    }
  };

  setPostSelectAll() {
    const {
      brand,
      project,
      person,
      brandPermisionData,
      projectPermisionData,
      personPermisionData,
    } = this.state;
    let val =
      brandPermisionData.length === brand.length &&
      projectPermisionData.length === project.length &&
      personPermisionData.length === person.length
        ? 1
        : 0;
    this.setState({
      postSelectAll: val,
    });
  }

  onBrandCheckChange = (list: any) => {
    const { brandPermisionData } = this.state;
    this.setState(
      {
        brandCheckAll: list.length === brandPermisionData.length,
        brand: list,
      },
      () => {
        // this.setPostSelectAll()
      },
    );
  };

  onBrandCheckAllChange = (e: any) => {
    const { brandPermisionData } = this.state;
    let tempCheckList: Array<any> = [];
    if (e.target.checked) {
      brandPermisionData.forEach((item: any) => {
        tempCheckList.push(item.value);
      });
    }
    this.setState(
      {
        brandCheckAll: e.target.checked,
        brand: tempCheckList,
      },
      () => {
        // this.setPostSelectAll()
      },
    );
  };

  onProjectCheckChange = (list: any) => {
    const { projectPermisionData } = this.state;
    this.setState(
      {
        projectCheckAll: list.length === projectPermisionData.length,
        project: list,
      },
      () => {
        // this.setPostSelectAll()
      },
    );
  };

  onProjectCheckAllChange = (e: any) => {
    const { projectPermisionData } = this.state;
    let tempCheckList: Array<any> = [];
    if (e.target.checked) {
      projectPermisionData.forEach((item: any) => {
        tempCheckList.push(item.value);
      });
    }
    this.setState(
      {
        projectCheckAll: e.target.checked,
        project: tempCheckList,
      },
      () => {
        // this.setPostSelectAll()
      },
    );
  };

  onPersonCheckChange = (list: any) => {
    const { personPermisionData } = this.state;
    this.setState(
      {
        personCheckAll: list.length === personPermisionData.length,
        person: list,
      },
      () => {
        // this.setPostSelectAll()
      },
    );
  };

  onPersonCheckAllChange = (e: any) => {
    const { personPermisionData } = this.state;
    let tempCheckList: Array<any> = [];
    if (e.target.checked) {
      personPermisionData.forEach((item: any) => {
        tempCheckList.push(item.value);
      });
    }
    this.setState(
      {
        personCheckAll: e.target.checked,
        person: tempCheckList,
      },
      () => {
        // this.setPostSelectAll()
      },
    );
  };

  handleEditAccount = (record: any) => {
    //  编辑账号
    this.setState({
      editAdminOpen: true,
      editAdminData: record
    });
  }

  handleDeleteAccount = (sid: string) => {
    //  删除账号
    const { dispatch } = this.props;
    dispatch({
      type: 'http/postDataWithRes',
      payload: { url: '/account/delete', sid },
      callback: (response: any) => {
        if (response.statusCode === '0') {
          message.success('删除成功');
          this.refresAdmin();
        }
      },
    });
  };

  handleResetAccountPwd = (record: any) => {
    //  重置账号密码
    this.setState({
      resetVisible: true,
      resetRecord: record,
    });
  };

  handleLockAccount = (sid: string) => {
    const { dispatch } = this.props;
    dispatch({
      type: 'http/postDataWithRes',
      payload: { url: '/account/lock', sid },
      callback: (response: any) => {
        if (response.statusCode === '0') {
          message.success('锁定成功');
          this.refresAdmin();
        }
      },
    });
  };

  handleUnlockAccount = (sid: string) => {
    //  解锁
    const { dispatch } = this.props;
    dispatch({
      type: 'http/postDataWithRes',
      payload: { url: '/account/unlock', sid },
      callback: (response: any) => {
        if (response.statusCode === '0') {
          message.success('解锁成功');
          this.refresAdmin();
        }
      },
    });
  };

  closeEditModal = () => {
    this.setState({
      editAdminOpen: false,
      editAdminData: null
    });
  }

  render() {
    const {
      tenant: {
        pageData: { list, pagination },
      },
      loading,
      detailLoading,
      saveLoading,
      location: { pathname = '/' },
    } = this.props;
    const {
      formValues,
      rsVisible,
      rsAdminVisible,
      rsList,
      rsAdminList,
      checkedKeys,
      adminCheckedKeys,
      expandedKeys,
      expandedAdminKeys,
      visible,
      postUrl,
      formData,
      adminVisible,
      adminList,
      modalVisible,
      tenantCode,
      tenantSid,
      tenantIsSelectAll,
      refreshLoading,
      isSelectAll,
      postSelectAll,
      activeTabKey,
      tabDisabled,
      brand,
      project,
      person,
      brandPermisionData,
      projectPermisionData,
      personPermisionData,
      brandCheckAll,
      projectCheckAll,
      personCheckAll,
      resetVisible,
      resetRecord,
      editAdminOpen,
      editAdminData,
      roleOption,
      orgOption,
    } = this.state;
    //登录模式,默认是1可重复登录
    formData.loginMode = 1;
    const columns = [
      {
        title: '序号',
        dataIndex: 'index',
        render: (text: any, record: any, index: any) => {
          return index + 1 + (pagination.current - 1) * pagination.pageSize;
        },
      },
      {
        title: '租户编码',
        dataIndex: 'tenantCode',
      },
      {
        title: '租户名称',
        dataIndex: 'tenantName',
      },
      {
        title: '租户描述',
        dataIndex: 'tenantDesc',
      },
      {
        title: '账号查询模式',
        dataIndex: 'mgrViewOtherAccount',
        render: (text: any) => {
          switch (String(text)) {
            case '0':
              return '共享查询';
            case '1':
              return '自建自查';
            default:
              break;
          }
          return text;
        },
      },
      {
        title: '角色查询模式',
        dataIndex: 'mgrViewOtherRole',
        render: (text: any) => {
          switch (String(text)) {
            case '0':
              return '共享查询';
            case '1':
              return '自建自查';
            default:
              break;
          }
          return text;
        },
      },
      // {
      //   title: '登录模式',
      //   dataIndex: 'loginMode',
      //   render: (text: any) => {
      //     switch (String(text)) {
      //       case '1':
      //         return '可重复登录';
      //       case '2':
      //         return '可重复登录(注销)';
      //       case '3':
      //         return '不可重复登录';
      //       default:
      //         break;
      //     }
      //     return text;
      //   },
      // },
      {
        title: '已关联账号',
        dataIndex: 'accountNum',
      },
      /* {
        title: '已关联角色',
        dataIndex: 'roleNum',
      }, */
      {
        title: '创建时间',
        dataIndex: 'createDate',
        render: (text: any) => {
          return text ? moment(text).format('YYYY-MM-DD HH:mm:ss') : null;
        },
      },
      {
        title: '操作',
        dataIndex: '操作',
        fixed: 'right',
        width: 140,
        render: (text: any, record: any) => {
          // if (record.tenantCode === 'opsystem') {
          //   if (formValues.tenantName !== '系统租户') {
          //     return '';
          //   }
          // }
          let btns = [
            {
              title: '编辑',
              key: 'edit',
              auth: 'tenant_doEdit',
              onConfirm: () => this.handleEdit(record),
            },
            {
              title: record.tenantCode === 'opsystem' ? '菜单管理' : '租户菜单管理',
              key: 'tenantMgr',
              auth: 'tenant_doResourceConfig',
              onConfirm: () => this.openResource(record.tenantCode),
            },
            {
              title: '管理员菜单管理',
              key: 'tenantMenuMgr',
              auth: 'tenant_doResourceConfig',
              onConfirm: () => this.openAdminResource(record.tenantCode),
            },
            {
              title: '管理员管理',
              key: 'tenantAdminMgr',
              auth: 'tenant_doFindMgr',
              onConfirm: () => this.openAdmin(record.tenantCode, record.sid, record.isSelectAll),
            },
          ];

          if (record.tenantCode === 'opsystem') {
            btns = btns.slice(0, -2);
          }

          return <PateoAuthButtons btns={btns} max={1} pathname={pathname} />;
        },
      },
    ];
    const adminColumns = [
      {
        title: '序号',
        dataIndex: 'index',
        width: 50,
        render: (text: any, record: any, index: any) => {
          return index + 1;
        },
      },
      {
        title: '登录账号',
        dataIndex: 'accountName',
      },
      {
        title: '账号类型',
        dataIndex: 'accountType',
        render: (text: any) => {
          switch (String(text)) {
            case '0':
              return '普通账号';
            case '1':
              return '租户管理员';
            case '2':
              return '超管';
            default:
              break;
          }
          return text;
        },
      },
      {
        title: '账号状态',
        dataIndex: 'accountStatus',
        render: (text: any) => {
          switch (String(text)) {
            case '0':
              return <Badge status="success" text="正常" />;
            case '1':
              return <Badge status="warning" text="锁定" />;
            case '2':
              return <Badge status="error" text="失效" />;
            default:
              break;
          }
          return text;
        },
      },
      {
        title: '登录类型',
        dataIndex: 'loginType',
        render: (text: any) => {
          switch (String(text)) {
            case '0':
              return '账号密码登录';
            case '1':
              return 'LDAP模式';
            case '2':
              return '飞书';
            default:
              break;
          }
          return text;
        },
      },
      {
        title: '操作',
        dataIndex: 'dataIndex',
        fixed: 'right',
        width: 140,
        render: (text: any, record: any) => {
          /* accountName: "matc_admin"
          accountStatus: 0
          accountType: 1
          loginType: 0
          sid: 84 */

          // tenant tenant_doResourceConfig
          const btns = [
             {
              title: '编辑',
              key: 'edit',
              auth: 'tenant_account_doEdit',
              onConfirm: () => this.handleEditAccount(record),
            },
            {
              title: '删除',
              key: 'del',
              auth: 'tenant_account_doDel',
              message: '是否确认删除？',
              Popconfirm: true,
              onConfirm: () => this.handleDeleteAccount(record.sid),
            },
            {
              title: '重置密码',
              key: 'resetPwd',
              auth: 'tenant_account_doResetPwd',
              onConfirm: () => this.handleResetAccountPwd(record),
            },
            /* {
              title: '解锁',
              key: 'unlock',
              auth: 'tenant_account_doUnlock',
              message: '是否确认解锁？',
              Popconfirm: true,
              onConfirm: () => this.handleUnlockAccount(record.sid),
            } */
          ];
          if (record.accountStatus === 0) {
            btns.push({
              title: '锁定',
              key: 'lock',
              auth: 'tenant_account_doLock',
              message: '是否确认锁定？',
              Popconfirm: true,
              onConfirm: () => this.handleLockAccount(record.sid),
            });
          } else if (record.accountStatus === 1) {
            btns.push({
              title: '解锁',
              key: 'unlock',
              auth: 'tenant_account_doUnlock',
              message: '是否确认解锁？',
              Popconfirm: true,
              onConfirm: () => this.handleUnlockAccount(record.sid),
            });
          }
          /* if (record.accountStatus === 1) {
            btns.push({
              title: '解锁',
              key: 'unlock',
              auth: 'tenant_account_doUnlock',
              message: '是否确认解锁？',
              Popconfirm: true,
              onConfirm: () => this.handleUnlockAccount(record.sid),
            });
          } */
          return <PateoAuthButtons btns={btns} max={2} pathname={pathname} />;
        },
      },
    ];
    const paginationProps = {
      showSizeChanger: true,
      showQuickJumper: true,
      ...pagination,
      showTotal: () => (
        <span>共&nbsp;{pagination === undefined ? 0 : pagination.total}&nbsp;条</span>
      ),
    };
    const tableProps = {
      columns,
      dataSource: list,
      loading,
      rowKey: (record: any) => record.tenantCode,
      pagination: paginationProps,
      scroll: { x: 'max-content' },
    };
    const searchItems = [
      {
        type: 'input',
        title: '租户名称',
        key: 'tenantName',
      },
      {
        type: 'select',
        title: '账号查询模式',
        key: 'mgrViewOtherAccount',
        selectOptions: [
          { value: '0', label: '共享查询' },
          { value: '1', label: '自建自查' },
        ],
      },
      /* {
        type: 'select',
        title: '角色查询模式',
        key: 'mgrViewOtherRole',
        selectOptions: [
          { value: '0', label: '共享查询' },
          { value: '1', label: '自建自查' },
        ],
      }, */
    ];
    const formItems = [
      {
        type: 'input',
        title: '租户名称',
        key: 'tenantName',
        rules: [{ required: true, message: comboHolder('租户名称'), whitespace: true }],
        maxLength: 30,
        onChange: e => {
          this.state.formData.tenantName = e.target.value;
        },
      },
      {
        type: 'input',
        title: '租户编码',
        key: 'tenantCode',
        rules: [{ required: true, message: comboHolder('租户编码'), whitespace: true }],
        maxLength: 8,
        editDisabled: true,
        onChange: e => {
          this.state.formData.tenantCode = e.target.value;
        },
      },
      // {
      //   type: 'select',
      //   title: '登录模式',
      //   key: 'loginMode',
      //   rules: [{ required: true, message: comboSelectHolder('登录模式') }],
      //   selectOptions: [
      //     { value: '1', label: '可重复登录' },
      //     { value: '2', label: '可重复登录(注销)' },
      //     { value: '3', label: '不可重复登录' }
      //   ]
      // },
      {
        type: 'custom',
        title: '租户LOGO',
        key: 'logoUrl',
        // editDisabled: false,
        // text: '上传',
        // fileMaxSize: 10,
        // uploadUrl: '/common/upload/all?checkSuffix=jpg,jpeg,png,gif,bmp',
        // listType: 'picture-card',
        // tag: 'text',
        // rules: [{ required: false, message: comboHolder('租户Logo'), whitespace: true }],
        item: () => {
          return (
            <Form.Item label={'租户LOGO'} name="logoUrl" {...itemLayout}>
              <div>
                <div
                  style={{
                    border: '1px solid #d9d9d9',
                    width: '100px',
                    height: '100px',
                    background: `url(${this.state.cropper.logoUrl}) no-repeat center/contain`,
                    display: 'flex',
                    justifyContent: 'center',
                    alignItems: 'center',
                  }}
                  onClick={() => {
                    // console.log('@@@', this.state.formData);
                    this.state.cropper.visible = true;
                    this.state.cropper.src = this.state.formData.logoUrl;
                    this.state.cropper.key = 'logoUrl';
                    this.setState({ cropper: { ...this.state.cropper } });
                  }}
                >
                  {!this.state.cropper.logoUrl ? <PlusOutlined /> : null}
                </div>
                <div
                  style={{
                    position: 'absolute',
                    top: 0,
                    left: '110px',
                    width: '100%',
                    height: '100px',
                    display: 'flex',
                    flexDirection: 'column',
                    justifyContent: 'space-between',
                    color: 'red',
                    fontSize: '12px',
                  }}
                >
                  <label>
                    <Tooltip title="上传成功后，logo将在左侧菜单栏上方显示">
                      <QuestionCircleOutlined />
                    </Tooltip>
                  </label>
                  <p style={{ margin: 0 }}>
                    建议尺寸比例 4:1
                    <br />
                    图片大小: 小于80KB
                  </p>
                </div>
              </div>
            </Form.Item>
          );
        },
      },
      {
        type: 'custom',
        title: '缩略LOGO',
        key: 'thumbnailLogoUrl',
        // editDisabled: false,
        // text: '上传',
        // fileMaxSize: 10,
        // uploadUrl: '/common/upload/all?checkSuffix=jpg,jpeg,png,gif,bmp',
        // listType: 'picture-card',
        // tag: 'text',
        // rules: [{ required: false, message: comboHolder('租户Logo'), whitespace: true }],
        item: () => {
          return (
            <Form.Item label={'缩略LOGO'} name="thumbnailLogoUrl" {...itemLayout}>
              <div
                style={{
                  position: 'relative',
                }}
              >
                <div
                  style={{
                    border: '1px solid #d9d9d9',
                    width: '100px',
                    height: '100px',
                    background: `url(${this.state.cropper.thumbnailLogoUrl}) no-repeat center/contain`,
                    display: 'flex',
                    justifyContent: 'center',
                    alignItems: 'center',
                  }}
                  onClick={() => {
                    // console.log('@@@', this.state.formData);
                    this.state.cropper.visible = true;
                    this.state.cropper.src = this.state.formData.thumbnailLogoUrl;
                    this.state.cropper.key = 'thumbnailLogoUrl';
                    this.setState({ cropper: { ...this.state.cropper } });
                  }}
                >
                  {!this.state.cropper.thumbnailLogoUrl ? <PlusOutlined /> : null}
                </div>
                <div
                  style={{
                    position: 'absolute',
                    top: 0,
                    left: '110px',
                    width: '100%',
                    height: '100px',
                    display: 'flex',
                    flexDirection: 'column',
                    justifyContent: 'space-between',
                    color: 'red',
                    fontSize: '12px',
                  }}
                >
                  <label>
                    <Tooltip title="页面进行缩放变化时，logo会自动切换为极简logo样式！">
                      <QuestionCircleOutlined />
                    </Tooltip>
                  </label>
                  <p style={{ margin: 0 }}>
                    建议尺寸比例 1:1
                    <br />
                    图片大小: 小于80KB
                  </p>
                </div>
              </div>
            </Form.Item>
          );
        },
      },
      /* {
        type: 'custom',
        title: '数据权限',
        key: 'isSelectAll',
        // rules: [{ required: true, message: '请选择数据权限' }],
        item: () => {
          return (
            <Form.Item label="数据权限" {...itemLayout}>
              <Radio.Group value={isSelectAll} onChange={(e) => {
                this.setState({
                  isSelectAll: e.target.value
                })
                this.onSelectAllChange(e.target.value)
              }}>
                <Radio value={0}>部分数据权限</Radio>
                <Radio value={1}>全量数据权限</Radio>
              </Radio.Group>
            </Form.Item>
          )
        }
      }, */
      {
        type: 'radio',
        title: '数据权限',
        key: 'isSelectAll',
        rules: [{ required: true, message: '请选择数据权限' }],
        options: [
          { value: 0, label: '部分数据权限' },
          { value: 1, label: '全量数据权限' },
        ],
        onChange: (e: any) => {
          const { formData, cropper } = this.state;
          this.setState({
            formData: {
              ...formData,
              isSelectAll: e.target.value, //  *
            },
          });
          this.onSelectAllChange(e.target.value);
        },
      },
      {
        type: 'custom',
        title: '数据权限',
        key: 'permissionList', //  dataPermission
        item: () => {
          //  formData.isSelectAll === 0 ? (<></>) : 0 ? (<></>)
          return (
            <div
              className={classnames(permissonStyle.permissonWrapper)}
              style={{
                maxHeight: formData.isSelectAll === 0 ? '666px' : '0px',
              }}
            >
              <Form.Item colon={false} label=" " {...itemLayout}>
                <div
                  style={{
                    position: 'relative',
                    height: '10px',
                  }}
                >
                  <span
                    style={{
                      position: 'absolute',
                      left: '30px',
                      bottom: '0px',
                      width: 0,
                      height: 0,
                      borderLeft: '6px solid transparent',
                      borderRight: '6px solid transparent',
                      borderBottom:
                        activeTabKey === 'brand' ? '12px solid #1890ff' : '12px solid #e5e5e5',
                    }}
                  ></span>
                </div>
                <div className={permissonStyle.dataPermisionBox}>
                  {/* 缩放浏览器器、tabBarGutter 设置为0为导致闪烁 */}
                  <Tabs
                    type="card"
                    activeKey={activeTabKey}
                    tabBarGutter={1}
                    onChange={key => {
                      this.setState({
                        activeTabKey: key,
                      });
                    }}
                  >
                    <Tabs.TabPane disabled={tabDisabled} tab="品牌" key="brand">
                      <Checkbox
                        disabled={tabDisabled}
                        onChange={this.onBrandCheckAllChange}
                        checked={brandCheckAll}
                      >
                        全选
                      </Checkbox>
                      <div>
                        <CheckboxGroup
                          disabled={tabDisabled}
                          options={brandPermisionData}
                          value={brand}
                          onChange={this.onBrandCheckChange}
                        />
                      </div>
                    </Tabs.TabPane>
                    <Tabs.TabPane disabled={tabDisabled} tab="项目" key="project">
                      <Checkbox
                        disabled={tabDisabled}
                        onChange={this.onProjectCheckAllChange}
                        checked={projectCheckAll}
                      >
                        全选
                      </Checkbox>
                      <div>
                        <CheckboxGroup
                          disabled={tabDisabled}
                          options={projectPermisionData}
                          value={project}
                          onChange={this.onProjectCheckChange}
                        />
                      </div>
                    </Tabs.TabPane>
                    <Tabs.TabPane disabled={tabDisabled} tab="人员" key="person">
                      <Checkbox
                        disabled={tabDisabled}
                        onChange={this.onPersonCheckAllChange}
                        checked={personCheckAll}
                      >
                        全选
                      </Checkbox>
                      <div>
                        <CheckboxGroup
                          disabled={tabDisabled}
                          options={personPermisionData}
                          value={person}
                          onChange={this.onPersonCheckChange}
                        />
                      </div>
                    </Tabs.TabPane>
                  </Tabs>
                </div>
              </Form.Item>
            </div>
          );
        },
      },
      /* {
        type: 'radio',
        title: '数据权限',
        key: 'isSelectAll',
        rules: [{ required: true, message: '请选择数据权限' }],
        options: [
          { value: 0, label: '部分数据权限' },
          { value: 1, label: '全量数据权限' },
        ]
      }, */
      /* {
        type: 'custom',
        title: '数据权限',
        key: 'dataPermission',
        rules: [{ required: false, message: '请选择数据权限' }],
        item: () => {
          return (
            
              <Form.Item name="isSelectAll" label="数据权限" {...itemLayout}>
                <Radio.Group>
                  <Radio value={0}>部分数据权限</Radio>
                  <Radio value={1}>全量数据权限</Radio>
                </Radio.Group>
              </Form.Item>
          )
        }
      }, */
      {
        type: 'select',
        title: '账号查询模式',
        key: 'mgrViewOtherAccount',
        rules: [{ required: true, message: comboSelectHolder('账号查询模式') }],
        selectOptions: [
          { value: '0', label: '共享查询' },
          { value: '1', label: '自建自查' },
        ],
        onChange: e => {
          this.state.formData.mgrViewOtherAccount = e;
        },
      },
      {
        type: 'select',
        title: '角色查询模式',
        key: 'mgrViewOtherRole',
        rules: [{ required: true, message: comboSelectHolder('角色查询模式') }],
        selectOptions: [
          { value: '0', label: '共享查询' },
          { value: '1', label: '自建自查' },
        ],
        onChange: e => {
          this.state.formData.mgrViewOtherRole = e;
        },
      },
      {
        type: 'textArea',
        title: '租户描述',
        key: 'tenantDesc',
        rules: [{ required: false, message: comboHolder('租户描述'), whitespace: true }],
        maxLength: 100,
        onChange: e => {
          this.state.formData.tenantDesc = e.target.value;
        },
      },
    ];

    return (
      <div>
        <Card bordered={false}>
          <PateoSearchForm
            searchItems={searchItems}
            fetchParams={{ type: 'tenant/postFetchPage', url: '/tenant/page' }}
            saveFormValues={(val: any) =>
              this.setState({ formValues: Object.assign(formValues, val) })
            }
            handleFormReset={() => this.setState({ formValues: {} })}
          />
        </Card>
        <Card className={styles.standardTable}>
          {filterAuth('tenant_doAdd', this.context.permissions, pathname) ? (
            <div className="my_newItem">
              <Button
                size="small"
                icon={<PlusOutlined />}
                type="primary"
                onClick={() => this.handleAdd()}
              >
                新增租户
              </Button>
            </div>
          ) : null}
          <PateoTable
            extraHandle={true}
            tableProps={tableProps}
            fetchParams={{ type: 'tenant/postFetchPage', url: '/tenant/page' }}
            formValues={formValues}
          />
        </Card>
        <Drawer
          title={
            <>
              租户菜单管理
              <Tooltip
                placement="bottom"
                title="取消某个菜单将使该租户下角色都取消此菜单，请慎重操作"
              >
                <ExclamationCircleFilled
                  style={{
                    marginLeft: 4,
                    transform: 'translateY(-15%)',
                    fontSize: 12,
                    color: 'orange',
                  }}
                />
              </Tooltip>
            </>
          }
          onClose={this.closeResource}
          visible={rsVisible}
          closable={false}
          width={500}
          extra={
            <Space>
              <Button size="small" onClick={this.closeResource}>
                取消
              </Button>
              <Button
                size="small"
                loading={saveLoading || detailLoading}
                onClick={this.onResourceSubmit}
                type="primary"
              >
                保存
              </Button>
            </Space>
          }
        >
          <Spin spinning={detailLoading} style={{ top: 30 }}>
            <Tree
              checkable
              onCheck={this.onCheck}
              onExpand={(keys: any) => this.setState({ expandedKeys: keys })}
              expandedKeys={expandedKeys}
              checkedKeys={checkedKeys}
            >
              {this.renderTreeNodes(rsList)}
            </Tree>
          </Spin>
        </Drawer>
        <Drawer
          title="管理员菜单管理"
          onClose={this.closeAdminResource}
          visible={rsAdminVisible}
          closable={false}
          width={500}
          extra={
            <Space>
              <Button size="small" onClick={this.closeAdminResource}>
                取消
              </Button>
              <Button
                size="small"
                loading={saveLoading}
                onClick={this.onAdminResourceSubmit}
                type="primary"
              >
                保存
              </Button>
            </Space>
          }
        >
          <Tree
            checkable
            onCheck={this.onAdminCheck}
            onExpand={(keys: any) => this.setState({ expandedAdminKeys: keys })}
            expandedKeys={expandedAdminKeys}
            checkedKeys={adminCheckedKeys}
          >
            {this.renderTreeNodes(rsAdminList)}
          </Tree>
        </Drawer>
        <Drawer
          title="管理员管理"
          onClose={this.closeAdmin}
          visible={adminVisible}
          closable={false}
          width={500}
          extra={
            <Button size="small" onClick={this.openModal} icon={<PlusOutlined />} type="primary">
              新增
            </Button>
          }
        >
          <Table
            bordered
            loading={refreshLoading || detailLoading}
            size="small"
            rowKey="sid"
            columns={adminColumns}
            dataSource={adminList}
            scroll={{ x: 'max-content' }}
            pagination={false}
          />
        </Drawer>
        <PateoModalForm
          style={{ top: '10%' }}
          formItems={formItems}
          changeVisible={() =>
            this.setState({
              formData: {},
              visible: false,
              postUrl: '',
              isSelectAll: 0,
              postSelectAll: 0,
              tabDisabled: false,
              activeTabKey: 'brand',
            })
          }
          // changeVisible={() => this.setState({formData: {}, visible: false, postUrl: ''})}
          formData={formData}
          visible={visible}
          postUrl={postUrl}
          handleCallback={this.handleFlushPage}
          handleModalFieldsValue={(values: any) => {
            const { brand, project, person, postSelectAll } = this.state;
            values.permissionList = {
              brand,
              project,
              person,
            };
            // values.isSelectAll = postSelectAll;
            values.logoUrl = this.state.cropper.logoUrl;
            values.thumbnailLogoUrl = this.state.cropper.thumbnailLogoUrl;
            // console.log('@@@', values);
            return values;
          }}
          customValidator={[{ validator: this.permissionValidator, msg: '请至少选择一项权限！' }]}
          title={['新增租户', '编辑租户']}
        />
        <ResetPwdModal
          modalVisible={resetVisible}
          record={resetRecord}
          refresAdmin={this.refresAdmin}
          closeModal={() => this.setState({ resetVisible: false, resetRecord: {} })}
        />
        {/* <EditModal
          onRef={(val: any) => (this.editForm = val)}
          modalVisible={editAdminOpen}
          roleOption={roleOption}
          orgOption={orgOption}
          closeModal={this.closeEditModal}
        /> */}
        <AddAdminModal
          modalVisible={modalVisible}
          closeModal={this.closeModal}
          refresAdmin={this.refresAdmin}
          tenantCode={tenantCode}
          tenantSid={tenantSid}
          isSelectAll={tenantIsSelectAll}
        />
        <EditAdminModal
          open={editAdminOpen}
          data={editAdminData}
          onClose={this.closeEditModal}
          dispatch={this.props.dispatch}
          refresAdmin={this.refresAdmin}
        />
        {this.state.cropper.visible ? (
          <PateoCropper
            aspectRatio={
              {
                logoUrl: 4,
                thumbnailLogoUrl: 1,
              }[this.state.cropper.key]
            }
            dispatch={this.props.dispatch}
            visible={this.state.cropper.visible}
            image={this.state.cropper.src}
            changeVisible={() => {
              this.state.cropper.visible = false;
              this.setState({ cropper: { ...this.state.cropper } });
            }}
            changeSize={80}
            handleOk={async (canvas: any) => {
              return new Promise(resolve => {
                canvas.toBlob((e: any) => {
                  // const size = e.size / 1024;
                  // console.log('@@ size', size);
                  // if (size > 80) {
                  //   message.error('图片大小不能大于 80KB');
                  //   resolve(false);
                  //   return;
                  // }
                  const data = new FormData();
                  data.set('file', e, `Cropper.png`);
                  this.props.dispatch({
                    type: 'http/postFormData',
                    payload: {
                      url: `/common/upload/all?fileType=1`,
                      formData: data,
                    },
                    callback: (e: any) => {
                      if (e.statusCode === '0') {
                        this.state.cropper[this.state.cropper.key] = e.data.fileUrl;
                        this.setState({ cropper: { ...this.state.cropper } });
                        resolve(true);
                      } else {
                        message.error(e.statusMessage);
                        resolve(false);
                      }
                      // console.log('@@', e);
                    },
                  });
                  return;
                });
              });
            }}
          />
        ) : null}
      </div>
    );
  }
}
export default connect(mapStateToProps)(Tenant);
